package cn.zhj.springboot.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.zhj.springboot.domain.User;
import cn.zhj.springboot.exception.CodeEnum;
import cn.zhj.springboot.exception.R;
import cn.zhj.springboot.mapper.UserMapper;
import cn.zhj.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TransferrecordServiceImpl transferrecordService;

    @Override
    public List<User> getUsers() {
        return userMapper.getUsers();
    }

    @Override
    @Transactional
    public R transfer(Long payerId, Long payeeId, Double money) {
        User payer = userMapper.getUserById(payerId);
        User payee = userMapper.getUserById(payeeId);
        if (payer != null && payee != null){
            if (payer.getMoney() >= money){
                payer.setMoney(payer.getMoney() - money);
                payee.setMoney(payee.getMoney() + money);
                userMapper.updateUser(payer);
                userMapper.updateUser(payee);
                transferrecordService.addTransferrecord(payerId, payeeId, money);
                return R.OK();
            } else {
                return R.FAIL(CodeEnum.INSUFFICIENT_BALANCE);
            }
        } else {
            return R.FAIL(CodeEnum.NOT_FOUND_USER);
        }
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    @Override
    public R doLogin(String userName, String password) {
        User user = userMapper.getUserByUserName(userName);
        if (user != null){
            if (user.getPassword().equals(password)){
                StpUtil.login(user.getId());
                return R.OK(user);
            } else {
                return R.FAIL(CodeEnum.USER_PWD_FAIL);
            }
        } else {
            return R.FAIL(CodeEnum.USER_USERNAME_FAIL);
        }
    }
}
